package com.behome.socket_proxy.config;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * GlobalExceptionHandler 全局异常捕获
 *
 * @author Ljy
 * @version 2023/06/17 10:26
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public String catchException(Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result catchMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String,Object> hashMap = new HashMap<>();
        for (ObjectError error : bindingResult.getAllErrors()) {
            FieldError fieldError = (FieldError) error;
            hashMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Result.fail(502, "参数校验异常，请检查请求参数",hashMap);
    }
}
